﻿using System;
using System.Windows.Controls;

#if SILVERLIGHT

using System.Windows.Browser;

#endif

namespace Songhay.Mvvm.Extensions
{
    /// <summary>
    /// Extensions of <see cref="System.Windows.Controls.Frame"/>.
    /// </summary>
    public static class FrameExtensions
    {
        /// <summary>
        /// Converts the <see cref="Frame"/> into a navigation content.
        /// </summary>
        /// <param name="frame">The frame.</param>
        /// <param name="page">The page.</param>
        public static void SetNavigationContent(this Frame frame, Page page)
        {
            if(frame == null) throw new ArgumentNullException("frame", "The Navigation Frame is null.");
            if(page == null) throw new ArgumentNullException("page", "The Page is null.");

            frame.Content = page;
        }

        /// <summary>
        /// Converts the <see cref="Frame" /> into a navigation content.
        /// </summary>
        /// <param name="frame">The frame.</param>
        /// <param name="location">The location.</param>
        public static void SetNavigationContent(this Frame frame, Uri location)
        {
            frame.SetNavigationContent(location, null);
        }

        /// <summary>
        /// Converts the <see cref="Frame" /> into a navigation content.
        /// </summary>
        /// <param name="frame">The frame.</param>
        /// <param name="location">The location.</param>
        /// <param name="locationFormatter">The location formatter.</param>
        public static void SetNavigationContent(this Frame frame, Uri location, Func<Uri, Uri> locationFormatter)
        {
            if(frame == null) throw new ArgumentNullException("frame", "The Navigation Frame is null.");
            if(location == null) throw new ArgumentNullException("location", "The Navigation location is null.");

            if(location.IsAbsoluteUri && location.Scheme.ToLower().StartsWith("http"))
            {
#if SILVERLIGHT
                HtmlPage.Window.Navigate(location, "_self");
                //TODO: consider configuring the "_blank" option.
#endif

#if !SILVERLIGHT
                throw new NotImplementedException("WPF Navigation does not conventionally support http.");
#endif
            }
            else
            {
                if (locationFormatter != null) location = locationFormatter.Invoke(location);
                frame.Navigate(location);
            }
        }

    }
}
